package khiem.gadgets.demo.client;

import khiem.gadgets.demo.client.CellListData;
import khiem.gadgets.demo.client.JSO.CalendarEvent;
import khiem.gadgets.demo.client.JSO.ResponseData;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.logical.shared.HighlightEvent;
import com.google.gwt.event.logical.shared.HighlightHandler;
import com.google.gwt.gadgets.client.DynamicHeightFeature;
import com.google.gwt.gadgets.client.Gadget;
import com.google.gwt.gadgets.client.NeedsDynamicHeight;
import com.google.gwt.gadgets.client.Gadget.ModulePrefs;
import com.google.gwt.gadgets.client.io.AuthorizationType;
import com.google.gwt.gadgets.client.io.GadgetsIo;
import com.google.gwt.gadgets.client.io.IoProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.gadgets.client.io.RequestOptions;
import com.google.gwt.gadgets.client.io.ResponseReceivedHandler;

import java.util.ArrayList;
import java.util.Date;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */

//Added comments at the end of each line to break up Eclipse's auto formatting.
@ModulePrefs(
title = "newgadget", 
directory_title = "newgadget")
public class newgadget extends Gadget<UserPrefs> implements NeedsDynamicHeight {
  
  public static final native void debug(String text) /*-{
    console.debug(text);
  }-*/;
  
  String restURL;
  DatePicker datePicker;
  CellListData cellList;
  
  DynamicHeightFeature heightFeature;
  
  @Override
  protected void init(UserPrefs preferences) {
    restURL = preferences.restURL().getValue();
    VerticalPanel vPanel = new VerticalPanel();
    
    datePicker = new DatePicker();
    // Set the default value
    Date today = new Date();
    datePicker.setValue(today, true);
    highlightDate();
    vPanel.add(datePicker);
    
    cellList = new CellListData();
    //dataProvider.addDataDisplay(cellList.getCellList());
    getEventData();
    vPanel.add(cellList);
    
    cellList.getPager().getScrollPanel().addScrollHandler(new ScrollHandler() {
      
      public void onScroll(ScrollEvent event) {
        // highlight date in datePicker
        // Window.alert("Scrolled to new position " + event.getRelativeElement().getInnerText());
      }
    });
    
    Button testBtn = new Button("Test rest service");
    vPanel.add(testBtn);
    testBtn.addClickHandler(new ClickHandler() {
      
      public void onClick(ClickEvent event) {
        // TODO Auto-generated method stub
        getEventDataTest();
      }
    });

    RootPanel.get().add(vPanel);
    heightFeature.adjustHeight();
  }

  /* (non-Javadoc)
   * @see com.google.gwt.gadgets.client.NeedsDynamicHeight#initializeFeature(com.google.gwt.gadgets.client.DynamicHeightFeature)
   */
  public void initializeFeature(DynamicHeightFeature feature) {
    this.heightFeature = feature;
  } 
  
  public void highlightDate() {
    GadgetsIo io = IoProvider.get();
    RequestOptions options = RequestOptions.newInstance();
    options.setAuthorizationType(AuthorizationType.SIGNED);
    options.setMethodType(MethodType.GET);
    Date fromDate = datePicker.getFirstDate();
    Date toDate = datePicker.getLastDate();
    io.makeRequestAsJso(restURL + "/calgad/hdays/" + fromDate.getTime() + "/" + toDate.getTime() + "/", new ResponseReceivedHandler<JavaScriptObject>() {
      public void onResponseReceived(ResponseReceivedEvent<JavaScriptObject> event) {
        // update datePicker to highlight dates
        ResponseData jso = (ResponseData) event.getResponse().getData();
        JavaScriptObject[] list = jso.getList();
        if (list.length < 1) return;
        Date fromDate = datePicker.getFirstDate();
        Date firstDateOfYear = new Date(fromDate.getYear(), 0, 1);
        int fromDateOffSet = CalendarUtil.getDaysBetween(firstDateOfYear, fromDate) + 1;
        for (JavaScriptObject day : list) {
          int highlightDate = Integer.parseInt(day.toString());
          int highlightDateOffset = highlightDate - fromDateOffSet;
          Date hlDate = CalendarUtil.copyDate(fromDate);
          CalendarUtil.addDaysToDate(hlDate, highlightDateOffset);
          datePicker.addStyleToDates("bold-date", hlDate);
        }     
      }
    }, options);
  }
  
  public void getEventData() {
    GadgetsIo io = IoProvider.get();
    RequestOptions options = RequestOptions.newInstance();
    options.setAuthorizationType(AuthorizationType.SIGNED);
    options.setMethodType(MethodType.GET);
    Date fromDate = datePicker.getFirstDate();
    Date toDate = datePicker.getLastDate();
    io.makeRequestAsJso(restURL + "/calgad/events/" + fromDate.getTime() + "/" + toDate.getTime() + "/", new ResponseReceivedHandler<JavaScriptObject>() {
      public void onResponseReceived(com.google.gwt.gadgets.client.io.ResponseReceivedHandler.ResponseReceivedEvent<JavaScriptObject> event) {
        // update list data provider
        EventDatabase database = EventDatabase.get();
        database.cleanUp();
        ResponseData jso = (ResponseData) event.getResponse().getData();
        JavaScriptObject[] list = jso.getList();
        if (list.length < 1) {
          // do something
          return;
        }
        String debugText = "";
        for (JavaScriptObject obj : list) {
          CalendarEvent calEvent = (CalendarEvent)obj;
          CalendarEventInfo eventInfo = new CalendarEventInfo(calEvent);
          database.addEvent(eventInfo);
          debugText += (calEvent.getSummary() + ", ");
        }
        newgadget.debug(debugText);
        newgadget.debug("database size: " + database.getDataProvider().getList().size());
        database.refreshDisplays();
        newgadget.debug("CellList rows: " + cellList.getCellList().getRowCount());
      }
    }, options);
    /*Date fromDate = new Date();
    Date toDate = (Date) fromDate.clone();
    CalendarUtil.addDaysToDate(toDate, 1);
    EventDatabase database = EventDatabase.get();
    for(int i = 1; i <= 20; i++) {
      CalendarEventInfo event = new CalendarEventInfo(String.valueOf(i), "Event"+i, "Event"+i+"_desc", String.valueOf(i), fromDate, toDate );
      database.addEvent(event);
      database.refreshDisplays();
    }*/
  }
  
  public void getEventDataTest() {
    GadgetsIo io = IoProvider.get();
    RequestOptions options = RequestOptions.newInstance();
    options.setAuthorizationType(AuthorizationType.SIGNED);
    options.setMethodType(MethodType.GET);
    Date fromDate = datePicker.getFirstDate();
    Date toDate = datePicker.getLastDate();
    io.makeRequestAsJso(restURL + "/calgad/events/" + fromDate.getTime() + "/" + toDate.getTime() + "/", new ResponseReceivedHandler<JavaScriptObject>() {
      public void onResponseReceived(com.google.gwt.gadgets.client.io.ResponseReceivedHandler.ResponseReceivedEvent<JavaScriptObject> event) {
        // update list data provider
        EventDatabase database = EventDatabase.get();
        database.cleanUp();
        ResponseData jso = (ResponseData) event.getResponse().getData();
        JavaScriptObject[] list = jso.getList();
        if (list.length < 1) {
          Window.alert("No result!");
          return;
        }
        Window.alert(list.length + " events!");
        for (JavaScriptObject obj : list) {
          CalendarEvent calEvent = (CalendarEvent)obj;
          CalendarEventInfo eventInfo = new CalendarEventInfo(calEvent);
          database.addEvent(eventInfo);
        }
        database.refreshDisplays();
      }
    }, options);
  }
}
